package cn.itrip.trade.controller;
import cn.itrip.pojo.ItripHotelOrder;
import cn.itrip.trade.config.AlipayConfig;
import cn.itrip.trade.service.PayService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by LENOVO on 2018/8/28.
 */
@Controller
@RequestMapping("/api")
public class AlipayController {
    @Resource
    private PayService payService;

    @RequestMapping(value = "/prepay/{orderNo}", method = RequestMethod.GET)
    public String prePay(@PathVariable String orderNo, Model model)
    {
        try {
            ItripHotelOrder itripHotelOrder=payService.getHotelOrder(orderNo);
            if(itripHotelOrder!=null)
            {
                model.addAttribute("hotelName",itripHotelOrder.getHotelname());
                model.addAttribute("roomId", itripHotelOrder.getRoomid());
                model.addAttribute("count", itripHotelOrder.getCount());
                model.addAttribute("payAmount",itripHotelOrder.getPayamount());
                return "pay";
            }
            else
            {
                return "notfound";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 提交支付请求
     * @param WIDout_trade_no
     * @param WIDsubject
     * @param WIDtotal_amount
     * @param response
     */
    @RequestMapping(value = "/pay", method = RequestMethod.POST,produces="application/xml", consumes="application/x-www-form-urlencoded")
    public void pay( String WIDout_trade_no,String WIDsubject,String WIDtotal_amount,HttpServletResponse response)
    {
        String timeout_express = "2m";
        String product_code = "QUICK_WAP_PAY";
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,  AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(WIDout_trade_no);
        model.setSubject(WIDsubject);
        model.setTotalAmount(WIDtotal_amount);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        alipay_request.setReturnUrl(AlipayConfig.return_url);
        try {
            String form = client.pageExecute(alipay_request).getBody();
            System.out.println(form);
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 异步通知
     * @param request
     * @param response
     */
    @RequestMapping(value = "/notify/", method = RequestMethod.POST,produces="application/xml", consumes="application/x-www-form-urlencoded")
    public void notify(HttpServletRequest request, HttpServletResponse response)
    {
        try {
            Map<String, String> params = new HashMap<>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
              valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
                params.put(name, valueStr);
            }
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no")
                    .getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes(
                    "ISO-8859-1"), "UTF-8");
            // 交易状态
            String trade_status = new String(request.getParameter("trade_status")
                    .getBytes("ISO-8859-1"), "UTF-8");

            boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY,  AlipayConfig.CHARSET, "RSA2");
            // 验 证 成 功
            if (verify_result) {
                if (trade_status.equals("TRADE_FINISHED")) {
                    if(!payService.processed(out_trade_no))
                    {
                        payService.paySuccess(out_trade_no, 1,trade_no);
                    }
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                    if(!payService.processed(out_trade_no))
                    {
                        payService.paySuccess(out_trade_no, 1,trade_no);
                    }
                }
                response.getWriter().println("success");
            } else {
                payService.payFailed(out_trade_no, 1,trade_no);
                response.getWriter().println("fail");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 同步通知
     */
    @RequestMapping(value = "/return/", method = RequestMethod.GET)
    public void returnInfo(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String,String> params = new HashMap<String,String>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            boolean verify_result = AlipaySignature.rsaCheckV1(params,AlipayConfig.ALIPAY_PUBLIC_KEY,  AlipayConfig.CHARSET, "RSA2");
            // 验 证 成 功
            String id=payService.getHotelOrder(out_trade_no).getId().toString();
            if (verify_result) {
                 if(!payService.processed(out_trade_no))
                 {
                    payService.paySuccess(out_trade_no, 1,trade_no);
                    response.sendRedirect(String.format(AlipayConfig.paymentSuccessUrl, out_trade_no,id));
                 }
            }
            else {
                payService.payFailed(out_trade_no, 1,trade_no);
                response.sendRedirect(String.format(AlipayConfig.paymentFailureUrl,out_trade_no));
            }
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
